const { pool } = require('../config/db');
const moment = require('moment');

/**
 * 获取当前室内环境数据
 */
async function getCurrentIndoorEnvironment(req, res) {
  try {
    // 从数据库获取最新的环境数据记录
    const [rows] = await pool.query(
      'SELECT * FROM environmental_status ORDER BY timestamp DESC LIMIT 1'
    );

    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '未找到环境数据'
      });
    }

    // 转换为前端需要的格式
    const data = rows[0];
    const indoorEnvironment = {
      temperature: parseFloat(data.temperature),
      humidity: parseFloat(data.humidity),
      airQualityIndex: parseFloat(data.air_quality),
      pirDetected: data.pir,
      lightLevel: parseFloat(data.light),
      pressure: parseFloat(data.pressure) / 100,
      measureTime: data.timestamp
    };

    res.json({
      success: true,
      data: indoorEnvironment
    });
  } catch (error) {
    console.error('获取室内环境数据失败:', error);
    res.status(500).json({
      success: false,
      message: '获取室内环境数据失败',
      error: error.message
    });
  }
}

/**
 * 获取室内环境历史数据
 */
async function getIndoorEnvironmentHistory(req, res) {
  try {
    // 获取查询参数
    const { timeRange = 'day', limit = 24 } = req.query;
    let startTime;
    let query;
    let queryParams;
    let isAggregated = false;

    // 根据时间范围确定查询起始时间和查询方式
    switch (timeRange) {
      case 'day':
        startTime = moment().subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss');
        query = 'SELECT * FROM environmental_status WHERE timestamp >= ? ORDER BY timestamp DESC LIMIT ?';
        queryParams = [startTime, parseInt(limit)];
        break;
      case 'week':
        // 一周显示前七天每天的平均数据
        startTime = moment().subtract(7, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss');
        query = `
          SELECT 
            DATE(timestamp) as date,
            AVG(temperature) as temperature,
            AVG(humidity) as humidity,
            AVG(air_quality) as air_quality,
            IF(SUM(pir = 'detected') > SUM(pir = 'none'), 'detected', 'none') as pir,
            AVG(light) as light,
            AVG(pressure) as pressure,
            MAX(timestamp) as timestamp
          FROM environmental_status 
          WHERE timestamp >= ?
          GROUP BY DATE(timestamp)
          ORDER BY date DESC
          LIMIT 7
        `;
        queryParams = [startTime];
        isAggregated = true;
        break;
      case 'month':
        // 一月显示前30天每天的平均数据
        startTime = moment().subtract(30, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss');
        query = `
          SELECT 
            DATE(timestamp) as date,
            AVG(temperature) as temperature,
            AVG(humidity) as humidity,
            AVG(air_quality) as air_quality,
            IF(SUM(pir = 'detected') > SUM(pir = 'none'), 'detected', 'none') as pir,
            AVG(light) as light,
            AVG(pressure) as pressure,
            MAX(timestamp) as timestamp
          FROM environmental_status 
          WHERE timestamp >= ?
          GROUP BY DATE(timestamp)
          ORDER BY date DESC
          LIMIT 30
        `;
        queryParams = [startTime];
        isAggregated = true;
        break;
      default:
        startTime = moment().subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss');
        query = 'SELECT * FROM environmental_status WHERE timestamp >= ? ORDER BY timestamp DESC LIMIT ?';
        queryParams = [startTime, parseInt(limit)];
    }

    // 从数据库获取历史数据
    const [rows] = await pool.query(query, queryParams);

    // 转换为前端需要的格式
    const historyData = rows.map(data => ({
      temperature: parseFloat(data.temperature),
      humidity: parseFloat(data.humidity),
      airQualityIndex: parseFloat(data.air_quality),
      pirDetected: data.pir,
      lightLevel: parseFloat(data.light),
      pressure: parseFloat(data.pressure) / 100,
      measureTime: isAggregated ? data.date : data.timestamp
    }));

    res.json({
      success: true,
      data: historyData
    });
  } catch (error) {
    console.error('获取室内环境历史数据失败:', error);
    res.status(500).json({
      success: false,
      message: '获取室内环境历史数据失败',
      error: error.message
    });
  }
}


/**
 * 获取环境舒适度评估
 */
async function getEnvironmentAssessment(req, res) {
  try {
    // 获取最新的环境数据
    const [rows] = await pool.query(
      'SELECT * FROM environmental_status ORDER BY timestamp DESC LIMIT 1'
    );

    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '未找到环境数据'
      });
    }

    const data = rows[0];
    const temperature = parseFloat(data.temperature);
    const humidity = parseFloat(data.humidity);
    const airQuality = parseFloat(data.air_quality);
    const light = parseFloat(data.light);
    const pressure = parseFloat(data.pressure) / 100;
    const pir = data.pir === '1' || data.pir === 'true';

    // 获取用户偏好设置（如果有用户ID）
    let userPreferences = {
      comfortTemperatureRange: [22, 28],
      comfortHumidityRange: [40, 65],
      acceptableAQILimit: 100,
      lightPreference: 3
    };

    if (req.user) {
      const [userRows] = await pool.query(
        'SELECT * FROM user_preferences WHERE user_id = ?',
        [req.user.id]
      );

      if (userRows.length > 0) {
        const userPref = userRows[0];
        userPreferences = {
          comfortTemperatureRange: [parseFloat(userPref.min_temperature), parseFloat(userPref.max_temperature)],
          comfortHumidityRange: [parseFloat(userPref.min_humidity), parseFloat(userPref.max_humidity)],
          acceptableAQILimit: parseFloat(userPref.acceptable_aqi_limit),
          lightPreference: parseInt(userPref.light_preference)
        };
      }
    }

    // 评估舒适度
    const temperatureStatus = temperature < userPreferences.comfortTemperatureRange[0] ? -1 :
                             temperature > userPreferences.comfortTemperatureRange[1] ? 1 : 0;
    
    const humidityStatus = humidity < userPreferences.comfortHumidityRange[0] ? -1 :
                          humidity > userPreferences.comfortHumidityRange[1] ? 1 : 0;
    
    const airQualityStatus = airQuality > userPreferences.acceptableAQILimit ? 1 : 0;
    
    // 光照状态评估（简化版）
    const lightStatus = light < 300 ? -1 : light > 1000 ? 1 : 0;
    
    // 气压状态评估（简化版）
    const pressureStatus = pressure < 990 ? -1 : pressure > 1030 ? 1 : 0;
    
    // 人体感应状态
    const pirStatus = pir ? 1 : 0;
    
    // 总体舒适度评估
    const isComfortable = temperatureStatus === 0 && humidityStatus === 0 && airQualityStatus === 0;
    
    // 生成改善建议
    const suggestions = [];
    
    if (temperatureStatus === -1) {
      suggestions.push('室内温度偏低，建议提高温度或增加保暖措施。');
    } else if (temperatureStatus === 1) {
      suggestions.push('室内温度偏高，建议降低温度或增加通风。');
    }
    
    if (humidityStatus === -1) {
      suggestions.push('室内湿度偏低，建议使用加湿器提高湿度。');
    } else if (humidityStatus === 1) {
      suggestions.push('室内湿度偏高，建议使用除湿设备或增加通风。');
    }
    
    if (airQualityStatus === 1) {
      suggestions.push('室内空气质量较差，建议开启空气净化器或增加通风。');
    }
    
    if (lightStatus === -1) {
      suggestions.push('室内光照不足，建议增加照明或打开窗帘。');
    } else if (lightStatus === 1) {
      suggestions.push('室内光照过强，建议调暗灯光或拉上窗帘。');
    }
    
    const assessment = {
      isComfortable,
      temperatureStatus,
      humidityStatus,
      airQualityStatus,
      lightStatus,
      pressureStatus,
      pirStatus,
      suggestions
    };

    res.json({
      success: true,
      data: assessment
    });
  } catch (error) {
    console.error('获取环境舒适度评估失败:', error);
    res.status(500).json({
      success: false,
      message: '获取环境舒适度评估失败',
      error: error.message
    });
  }
}

/**
 * 获取环境趋势预测
 */
async function getEnvironmentPrediction(req, res) {
  try {
    // 获取最近的环境数据用于趋势分析
    const [rows] = await pool.query(
      'SELECT * FROM environmental_status ORDER BY timestamp DESC LIMIT 24'
    );

    if (rows.length < 6) { // 至少需要6条记录进行简单趋势分析
      return res.json({
        success: true,
        data: []
      });
    }

    // 简单的趋势分析
    const predictions = [];
    
    // 分析温度趋势
    const temperatures = rows.map(r => parseFloat(r.temperature)).reverse();
    const tempDiff = temperatures[temperatures.length - 1] - temperatures[0];
    if (tempDiff > 2) {
      predictions.push('温度呈上升趋势，预计未来几小时内室内温度将继续升高。');
    } else if (tempDiff < -2) {
      predictions.push('温度呈下降趋势，预计未来几小时内室内温度将继续降低。');
    }
    
    // 分析湿度趋势
    const humidities = rows.map(r => parseFloat(r.humidity)).reverse();
    const humidDiff = humidities[humidities.length - 1] - humidities[0];
    if (humidDiff > 10) {
      predictions.push('湿度呈上升趋势，预计未来几小时内室内湿度将继续增加。');
    } else if (humidDiff < -10) {
      predictions.push('湿度呈下降趋势，预计未来几小时内室内湿度将继续降低。');
    }
    
    // 分析空气质量趋势
    const airQualities = rows.map(r => parseFloat(r.air_quality)).reverse();
    const aqiDiff = airQualities[airQualities.length - 1] - airQualities[0];
    if (aqiDiff > 15) {
      predictions.push('空气质量呈恶化趋势，建议开启空气净化设备。');
    } else if (aqiDiff < -15) {
      predictions.push('空气质量呈改善趋势，室内空气质量正在好转。');
    }

    res.json({
      success: true,
      data: predictions
    });
  } catch (error) {
    console.error('获取环境趋势预测失败:', error);
    res.status(500).json({
      success: false,
      message: '获取环境趋势预测失败',
      error: error.message
    });
  }
}

/**
 * 添加新的环境数据记录
 */
async function addEnvironmentRecord(req, res) {
  try {
    const { device_id, temperature, humidity, air_quality, pir, light, pressure, bmp_temperature } = req.body;
    
    if (!device_id) {
      return res.status(400).json({
        success: false,
        message: '设备ID是必需的'
      });
    }
    
    // 插入新记录
    const [result] = await pool.query(
      'INSERT INTO environmental_status (device_id, temperature, humidity, air_quality, pir, light, pressure, bmp_temperature) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
      [device_id, temperature, humidity, air_quality, pir, light, pressure, bmp_temperature]
    );

    res.status(201).json({
      success: true,
      message: '环境数据记录已添加',
      data: {
        id: result.insertId,
        device_id,
        timestamp: new Date()
      }
    });
  } catch (error) {
    console.error('添加环境数据记录失败:', error);
    res.status(500).json({
      success: false,
      message: '添加环境数据记录失败',
      error: error.message
    });
  }
}

/**
 * 获取特定时间范围的环境数据
 */
async function getEnvironmentDataByRange(req, res) {
  try {
    const { startDate, endDate, interval = 'hour' } = req.query;
    
    if (!startDate || !endDate) {
      return res.status(400).json({
        success: false,
        message: '开始日期和结束日期是必需的'
      });
    }
    
    let query;
    let params;
    
    // 根据不同的时间间隔聚合数据
    switch (interval) {
      case 'hour':
        query = `
          SELECT 
            DATE_FORMAT(timestamp, '%Y-%m-%d %H:00:00') as time_interval,
            AVG(temperature) as avg_temperature,
            AVG(humidity) as avg_humidity,
            AVG(air_quality) as avg_air_quality,
            AVG(light) as avg_light,
            AVG(pressure) as avg_pressure
          FROM environmental_status
          WHERE timestamp BETWEEN ? AND ?
          GROUP BY time_interval
          ORDER BY time_interval ASC
        `;
        break;
      case 'day':
        query = `
          SELECT 
            DATE_FORMAT(timestamp, '%Y-%m-%d') as time_interval,
            AVG(temperature) as avg_temperature,
            AVG(humidity) as avg_humidity,
            AVG(air_quality) as avg_air_quality,
            AVG(light) as avg_light,
            AVG(pressure) as avg_pressure
          FROM environmental_status
          WHERE timestamp BETWEEN ? AND ?
          GROUP BY time_interval
          ORDER BY time_interval ASC
        `;
        break;
      default:
        query = `
          SELECT 
            timestamp as time_interval,
            temperature as avg_temperature,
            humidity as avg_humidity,
            air_quality as avg_air_quality,
            light as avg_light,
            pressure as avg_pressure
          FROM environmental_status
          WHERE timestamp BETWEEN ? AND ?
          ORDER BY timestamp ASC
        `;
    }
    
    params = [startDate, endDate];
    
    const [rows] = await pool.query(query, params);

    res.json({
      success: true,
      data: rows
    });
  } catch (error) {
    console.error('获取环境数据范围失败:', error);
    res.status(500).json({
      success: false,
      message: '获取环境数据范围失败',
      error: error.message
    });
  }
}

/**
 * 获取环境数据统计信息
 */
async function getEnvironmentStatistics(req, res) {
  try {
    const { period = 'day' } = req.query;
    let startDate;
    
    // 确定统计周期的开始日期
    switch (period) {
      case 'day':
        startDate = moment().subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss');
        break;
      case 'week':
        startDate = moment().subtract(7, 'days').format('YYYY-MM-DD HH:mm:ss');
        break;
      case 'month':
        startDate = moment().subtract(30, 'days').format('YYYY-MM-DD HH:mm:ss');
        break;
      default:
        startDate = moment().subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss');
    }
    
    // 查询统计数据
    const [rows] = await pool.query(`
      SELECT 
        AVG(temperature) as avg_temperature,
        MIN(temperature) as min_temperature,
        MAX(temperature) as max_temperature,
        AVG(humidity) as avg_humidity,
        MIN(humidity) as min_humidity,
        MAX(humidity) as max_humidity,
        AVG(air_quality) as avg_air_quality,
        MIN(air_quality) as min_air_quality,
        MAX(air_quality) as max_air_quality,
        AVG(light) as avg_light,
        AVG(pressure) as avg_pressure
      FROM environmental_status
      WHERE timestamp >= ?
    `, [startDate]);

    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '未找到统计数据'
      });
    }

    // 计算舒适度时间百分比
    const [comfortRows] = await pool.query(`
      SELECT 
        COUNT(*) as total_records,
        SUM(CASE WHEN temperature BETWEEN 22 AND 28 AND humidity BETWEEN 40 AND 65 AND air_quality <= 100 THEN 1 ELSE 0 END) as comfortable_records
      FROM environmental_status
      WHERE timestamp >= ?
    `, [startDate]);

    const totalRecords = comfortRows[0].total_records;
    const comfortableRecords = comfortRows[0].comfortable_records;
    const comfortPercentage = totalRecords > 0 ? (comfortableRecords / totalRecords) * 100 : 0;

    // 构建统计结果
    const statistics = {
      temperature: {
        average: parseFloat(rows[0].avg_temperature),
        minimum: parseFloat(rows[0].min_temperature),
        maximum: parseFloat(rows[0].max_temperature)
      },
      humidity: {
        average: parseFloat(rows[0].avg_humidity),
        minimum: parseFloat(rows[0].min_humidity),
        maximum: parseFloat(rows[0].max_humidity)
      },
      airQuality: {
        average: parseFloat(rows[0].avg_air_quality),
        minimum: parseFloat(rows[0].min_air_quality),
        maximum: parseFloat(rows[0].max_air_quality)
      },
      light: {
        average: parseFloat(rows[0].avg_light)
      },
      pressure: {
        average: parseFloat(rows[0].avg_pressure)
      },
      comfort: {
        percentage: comfortPercentage.toFixed(2)
      }
    };

    res.json({
      success: true,
      data: statistics
    });
  } catch (error) {
    console.error('获取环境数据统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取环境数据统计失败',
      error: error.message
    });
  }
}

/**
 * 获取特定设备的当前环境数据
 */
async function getDeviceEnvironmentData(req, res) {
  try {
    const { deviceId } = req.params;
    
    if (!deviceId) {
      return res.status(400).json({
        success: false,
        message: '设备ID是必需的'
      });
    }

    
    // 尝试两种方式查询设备环境数据
    let rows;
    
    // 首先尝试使用device_id字段查询
    [rows] = await pool.query(
      'SELECT * FROM environmental_status WHERE device_id = ? ORDER BY timestamp DESC LIMIT 1',
      [deviceId]
    );
    
    // 如果没有找到数据，可能是因为environmental_status表中的device_id是数字类型，
    // 而前端传来的是字符串，或者相反
    if (rows.length === 0) {
      // 尝试使用转换后的ID查询
      const numericId = Number(deviceId);
      if (!isNaN(numericId)) {
        [rows] = await pool.query(
          'SELECT * FROM environmental_status WHERE device_id = ? ORDER BY timestamp DESC LIMIT 1',
          [numericId]
        );
      }
    }

    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '未找到该设备的环境数据'
      });
    }

    // 转换为前端需要的格式
    const data = rows[0];
    const indoorEnvironment = {
      temperature: parseFloat(data.temperature),
      humidity: parseFloat(data.humidity),
      airQualityIndex: parseFloat(data.air_quality),
      pirDetected: data.pir,
      lightLevel: parseFloat(data.light),
      pressure: parseFloat(data.pressure) / 100,
      measureTime: data.timestamp
    };

    res.json({
      success: true,
      data: indoorEnvironment
    });
  } catch (error) {
    console.error('获取设备环境数据失败:', error);
    res.status(500).json({
      success: false,
      message: '获取设备环境数据失败',
      error: error.message
    });
  }
}

/**
 * 获取特定设备的环境历史数据
 */
async function getDeviceEnvironmentHistory(req, res) {
  try {
    const { deviceId } = req.params;
    const { timeRange = 'day', limit = 24 } = req.query;
    
    if (!deviceId) {
      return res.status(400).json({
        success: false,
        message: '设备ID是必需的'
      });
    }
    
    let startTime;
    let query;
    let queryParams;
    let isAggregated = false;

    // 根据时间范围确定查询起始时间和查询方式
    switch (timeRange) {
      case 'day':
        startTime = moment().subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss');
        query = 'SELECT * FROM environmental_status WHERE device_id = ? AND timestamp >= ? ORDER BY timestamp DESC LIMIT ?';
        queryParams = [deviceId, startTime, parseInt(limit)];
        break;
      case 'week':
        // 一周显示前七天每天的平均数据
        startTime = moment().subtract(7, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss');
        query = `
          SELECT 
            DATE(timestamp) as date,
            AVG(temperature) as temperature,
            AVG(humidity) as humidity,
            AVG(air_quality) as air_quality,
            IF(SUM(pir = 'detected') > SUM(pir = 'none'), 'detected', 'none') as pir,
            AVG(light) as light,
            AVG(pressure) as pressure,
            MAX(timestamp) as timestamp
          FROM environmental_status 
          WHERE device_id = ? AND timestamp >= ?
          GROUP BY DATE(timestamp)
          ORDER BY date DESC
          LIMIT 7
        `;
        queryParams = [deviceId, startTime];
        isAggregated = true;
        break;
      case 'month':
        // 一月显示前30天每天的平均数据
        startTime = moment().subtract(30, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss');
        query = `
          SELECT 
            DATE(timestamp) as date,
            AVG(temperature) as temperature,
            AVG(humidity) as humidity,
            AVG(air_quality) as air_quality,
            IF(SUM(pir = 'detected') > SUM(pir = 'none'), 'detected', 'none') as pir,
            AVG(light) as light,
            AVG(pressure) as pressure,
            MAX(timestamp) as timestamp
          FROM environmental_status 
          WHERE device_id = ? AND timestamp >= ?
          GROUP BY DATE(timestamp)
          ORDER BY date DESC
          LIMIT 30
        `;
        queryParams = [deviceId, startTime];
        isAggregated = true;
        break;
      default:
        startTime = moment().subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss');
        query = 'SELECT * FROM environmental_status WHERE device_id = ? AND timestamp >= ? ORDER BY timestamp DESC LIMIT ?';
        queryParams = [deviceId, startTime, parseInt(limit)];
    }

    // 执行查询
    let [rows] = await pool.query(query, queryParams);
    
    // 如果没有找到数据，可能是因为environmental_status表中的device_id是数字类型，
    // 而前端传来的是字符串，或者相反
    if (rows.length === 0) {
      // 尝试使用转换后的ID查询
      const numericId = Number(deviceId);
      if (!isNaN(numericId)) {
        queryParams[0] = numericId;
        [rows] = await pool.query(query, queryParams);
      }
    }

    // 转换为前端需要的格式
    const historyData = rows.map(data => ({
      temperature: parseFloat(data.temperature),
      humidity: parseFloat(data.humidity),
      airQualityIndex: parseFloat(data.air_quality),
      pirDetected: data.pir,
      lightLevel: parseFloat(data.light),
      pressure: parseFloat(data.pressure) / 100,
      measureTime: isAggregated ? data.date : data.timestamp
    }));

    res.json({
      success: true,
      data: historyData
    });
  } catch (error) {
    console.error('获取设备环境历史数据失败:', error);
    res.status(500).json({
      success: false,
      message: '获取设备环境历史数据失败',
      error: error.message
    });
  }
}

module.exports = {
  getCurrentIndoorEnvironment,
  getIndoorEnvironmentHistory,
  getEnvironmentAssessment,
  getEnvironmentPrediction,
  addEnvironmentRecord,
  getEnvironmentDataByRange,
  getEnvironmentStatistics,
  getDeviceEnvironmentData,
  getDeviceEnvironmentHistory
};